package com.nz2004.smsplatform.strategy.service.impl;


import com.nz2004.smsplatform.common.constants.CacheConstants;
import com.nz2004.smsplatform.common.constants.OperatorConstants;
import com.nz2004.smsplatform.common.constants.StrategyConstants;
import com.nz2004.smsplatform.common.index.StandardSubmit;
import com.nz2004.smsplatform.strategy.service.FilterChain;
import com.nz2004.smsplatform.strategy.service.api.CacheService;
import com.nz2004.smsplatform.strategy.util.CheckMobileOperator;
import com.nz2004.smsplatform.strategy.util.PushMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;

/**
 * @author ReJoice
 */
@Service("mobilePhase")
@Slf4j
public class MobilePhaseStrategy implements FilterChain {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private PushMessageUtil pushMessage;


    @Override
    public boolean strategy(StandardSubmit submit) {
        log.info("【号段补全策略】 号段补全策略执行了....");
        String mobile = submit.getDestMobile();

        //--------------------------------------------------------------
        //-------------------------搞定运营商-------------------------------------
        //--------------------------------------------------------------
        // 通过CheckMobileOperator工具类判断当前手机号的运营商
        if(CheckMobileOperator.isChinaMobilePhoneNum(mobile)){
            // 是移动
            submit.setOperatorId(OperatorConstants.CHINA_MOBILE);
        }else if(CheckMobileOperator.isChinaUnicomPhoneNum(mobile)){
            // 是联通
            submit.setOperatorId(OperatorConstants.CHINA_UNICOM);
        }else if(CheckMobileOperator.isChinaTelecomPhoneNum(mobile)){
            // 是电信
            submit.setOperatorId(OperatorConstants.CHINA_TELECOM);
        }else{
            // 国外号码
            submit.setOperatorId(OperatorConstants.CHINA_UNKNOWN);
        }


        //--------------------------------------------------------------
        //-------------------------搞定省市-------------------------------------
        //--------------------------------------------------------------
        //1. 获取手机号对应的省市
        String provinceAndCity = cacheService.get(CacheConstants.CACHE_PREFIX_PHASE + mobile.substring(0,7));
        //2. 非空判断
        if(StringUtils.isEmpty(provinceAndCity)){
            submit.setProvinceId(0);
            submit.setCityId(0);
            // TODO  之前的return true.会导致无法执行补齐管道选择,删掉,加上else
        }else {
            //3. 不为空,使用","进行分割
            int index = provinceAndCity.indexOf(",");
            String provinceId = provinceAndCity.substring(0, index);
            String cityId = provinceAndCity.substring(index + 1);
            //4. 设置到submit中
            submit.setProvinceId(Integer.valueOf(provinceId));
            submit.setCityId(Integer.valueOf(cityId));
        }
        //------------------------------------------------------
        //---------------------补齐管道选择---------------------------------
        // 也可以将channel以运营商分类,存放在list/set结构中.
        //------------------------------------------------------

        // 根据运营商id查询出当前平台所有可用的channel ->   (CLIENT:1:1)
        Set<String> keys = cacheService.keys(CacheConstants.CACHE_PREFIX_SMS_CHANNEL + submit.getOperatorId() + ":*");
        if(keys == null || keys.size() == 0){
            log.info("【号段补全策略】 策略校验失败，当前平台没有可用的通道发送消息给当前手机  mobile = {}",submit.getDestMobile());
            pushMessage.pushLog(submit, StrategyConstants.STRATEGY_ERROR_PHASE);
            pushMessage.pushReport(submit, StrategyConstants.STRATEGY_ERROR_PHASE);
            return false;
        }

        // 根据查询出的key,查询出指定的channel信息   ->    channelid ->
        for (String key : keys) {
            //1. 根据key查询出Channel信息
            Map channelMap = cacheService.hMGet(key);
            //2. 获取当前channel的id
            String id = (String) channelMap.get("id");
            // 根据当前channelid查询出client_channel信息  ROUTER:clientID:channelID
            Map clientChannel = cacheService.hMGet(CacheConstants.CACHE_PREFIX_ROUTER + submit.getClientID() + ":" + id);
            if(clientChannel != null && clientChannel.size() != 0){
                // 拿到了指定的客户管道信息
                // 封装下发源号码.
                submit.setSrcNumber((String) channelMap.get("spnumber") + clientChannel.get("extendnumber"));
                // 封装费用到submit(在Submit对象中追加一个属性)
                submit.setFee(Long.parseLong((String)clientChannel.get("price")));
                // 补全GatewayID
                submit.setGatewayID(Integer.valueOf((String)channelMap.get("id")));
                log.info("【号段补全策略】 号段补全成功");
                return true;
            }
        }
        // 判断是否找到了可用的管道信息,没找到
        log.info("【号段补全策略】 策略校验失败，客户没有绑定相应的管道信息..  mobile = {}",submit.getDestMobile());
        pushMessage.pushLog(submit, StrategyConstants.STRATEGY_ERROR_PHASE);
        pushMessage.pushReport(submit, StrategyConstants.STRATEGY_ERROR_PHASE);
        return false;
    }


}
